<template>
  <el-dialog
    title="忘记密码"
    :visible.sync="dialogPwdVisible"
    width="600px"
    :close-on-click-modal="false"
  >
    <el-form ref="ruleForm" :inline="false" :model="modifyForm" size="mini">
      <el-form-item
        label="手机号码"
        prop="phone"
        :rules="[{ required: true, validator: valiPhone, trigger: 'blur' }]"
      >
        <el-input v-model="modifyForm.phone" maxlength="11" />
      </el-form-item>
      <el-form-item
        label="验证码"
        prop="code"
        :rules="[{ required: true, message: '请输入验证码', trigger: 'blur' }]"
      >
        <el-input v-model="modifyForm.code" placeholder="请输入验证码">
          <el-button
            slot="append"
            type="primary"
            @click="smsSend"
            size="mini"
            >{{ state.sendTimeText }}</el-button
          >
        </el-input>
      </el-form-item>
      <el-form-item
        label="新的密码"
        prop="newPwd"
        :rules="[
          { required: true, validator: validatorNewPwd, trigger: 'blur' }
        ]"
      >
        <el-input
          :type="newPwdType"
          ref="newPwd"
          :placeholder="tips"
          :disabled="isReg"
          v-model="modifyForm.newPwd"
          autocomplete="new-password"
        />
        <span class="show-pwd" @click="showPwd('newPwd')">
          <svg-icon
            :icon-class="newPwdType === 'password' ? 'eye' : 'eye-open'"
          />
        </span>
      </el-form-item>
      <el-form-item
        label="确认密码"
        prop="pwd"
        :rules="[{ required: true, validator: validatorPwd, trigger: 'blur' }]"
      >
        <el-input
          :type="pwdType"
          ref="pwd"
          :disabled="isReg"
          v-model="modifyForm.pwd"
          autocomplete="new-password"
        />
        <span class="show-pwd" @click="showPwd('pwd')">
          <svg-icon :icon-class="pwdType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="mini" @click="dialogPwdVisible = false">取消</el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="submitForm('ruleForm')"
        size="mini"
        >确定</el-button
      >
    </span>
  </el-dialog>
</template>
<script>
import { mapGetters } from "vuex";
import { forgotPwd } from "@/api/system_api";
import { getPhoneCode } from "@/api/supplier_api";
import { loginMD5, checkPhone,checkPwd } from "@/utils/index";
export default {
  data() {
    return {
      dialogPwdVisible: false,
      pwdType: "password",
      newPwdType: "password",
      tips: "",
      modifyForm: {
        phone: "",
        code: "",
        pwd: "",
        newPwd: ""
      },
      loading: false,
      state: {
        sendTimeText: "获取验证码",
        isSendState: false,
        timeCounter: null,
        countdown: 60
      },
      isReg: true
    };
  },
  computed: {
    ...mapGetters(["smsType"])
  },
  methods: {
    open() {
      this.pwdType = "password";
      this.newPwdType = "password";
      this.tips = "";
      this.modifyForm.phone = "";
      this.modifyForm.code = "";
      this.modifyForm.pwd = "";
      this.modifyForm.newPwd = "";
      this.isReg = true;
      this.clartTime();
      this.dialogPwdVisible = true;
    },
    validatorNewPwd(rule, value, callback) {
      if (!value) {
        callback(new Error("请输入新密码"));
      } else {
        let size1 = checkPwd(value);///^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,}$/.test(value);
        if (!size1) {
          callback(new Error("登录密码不少于8位，必须数字+字母+特殊字符组合"));
        }
        if (this.modifyForm.pwd && this.modifyForm.pwd !== value) {
          callback(new Error("新密码和确认密码不一致"));
        }
        callback();
      }
    },
    validatorPwd(rule, value, callback) {
      if (!value) {
        callback(new Error("请输入确认密码"));
      } else {
        let size1 = checkPwd(value);// /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,}$/.test(value);
        if (!size1) {
          callback(new Error("登录密码不少于8位，必须数字+字母+特殊字符组合"));
        }
        if (this.modifyForm.newPwd && this.modifyForm.newPwd !== value) {
          callback(new Error("确认密码和新密码不一致"));
        }
        callback();
      }
    },
    valiPhone(rule, value, callback) {
      if (!value) {
        return callback(new Error("请输入联系电话"));
      }
      let size = checkPhone(value);
      if (!size) {
        callback(new Error("联系电话输入格式有误"));
      }
      callback();
    },
    showPwd(type) {
      if (type === "newPwd") {
        if (!this.modifyForm.newPwd) {
          return;
        }
        if (this.newPwdType === "password") {
          this.newPwdType = "";
        } else {
          this.newPwdType = "password";
        }
        this.$nextTick(() => {
          this.$refs.newPwd.focus();
        });
      } else if (type === "pwd") {
        if (!this.modifyForm.pwd) {
          return;
        }
        if (this.pwdType === "password") {
          this.pwdType = "";
        } else {
          this.pwdType = "password";
        }
        this.$nextTick(() => {
          this.$refs.pwd.focus();
        });
      }
    },
    async smsSend() {
      if (this.state.isSendState) {
        this.$message.error("不能重复发送");
        return;
      }
      if (!this.modifyForm.phone) {
        this.$message.error("请输入联系电话");
        return;
      }
      let size = checkPhone(this.modifyForm.phone);
      if (!size) {
        this.$message.error("联系电话输入格式有误");
        return;
      }
      let param = {};
      param.phone = this.modifyForm.phone;
      param.type = this.smsType["forgotPwd"];
      const { code } = await getPhoneCode(param);
      if (code == 200) {
        this.state.isSendState = true;
        this.isReg = false;
        this.settime();
      }
    },
    settime() {
      let that = this;
      if (this.state.countdown == 0) {
        this.clartTime();
        return false;
      } else {
        this.state.sendTimeText = "倒计时(" + this.state.countdown + ")s";
        this.state.countdown--;
      }
      this.state.timeCounter = setTimeout(function() {
        that.settime();
      }, 1000);
    },
    submitForm(formName) {
      let that = this;
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const pwd = this.modifyForm.newPwd + process.env.VUE_APP_FILE_Name;
          let params = {
            newPwd: loginMD5(pwd),
            phone: this.modifyForm.phone,
            code: this.modifyForm.code
          };
          this.loading = true;
          try {
            let req = await forgotPwd(params);
            if (req.code === 200) {
              this.$confirm("密码找回成功，请登陆系统。", "温馨提示", {
                confirmButtonText: "关闭",
                cancelButtonText: "取消",
                showCancelButton: false,
                type: "success"
              })
                .then(() => {
                  that.$refs["ruleForm"].resetFields();
                  that.dialogPwdVisible = false;
                  that.clartTime();
                })
                .catch(() => {});
            }
          } finally {
            this.loading = false;
          }
        } else {
          return false;
        }
      });
    },
    clartTime() {
      clearTimeout(this.state.timeCounter);
      this.state.isSendState = false;
      this.state.sendTimeText = "获取验证码";
      this.state.countdown = 60;
    }
  }
};
</script>
<style scoped>
.show-pwd {
  position: absolute;
  right: 14px;
  top: 30px;
  z-index: 999;
  cursor: pointer;
}
</style>
